package com.zhang.crm.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhang.crm.constant.Constants;

import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    //生成jwt:
    public static String createJWT(String jsonVal){
        //头部组装
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ","JWT");
        //链式编程
        return JWT.create()
                //头部
                .withHeader(header)

                //负载
                .withClaim("user",jsonVal)

                //签名
                .sign(Algorithm.HMAC256(Constants.SECRET));
    }


    //验证jwt:
    public static Boolean verifyJWT(String jwt){
        try{
            //创建验证器
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build();

            //验证
            jwtVerifier.verify(jwt);  //抛出异常则匹配失败

            return true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;

    }

    //解析jwt：
    public static String parseJWT(String jwt){
        try {
            //创建解析对象
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(Constants.SECRET)).build();
            //验证jwt
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
            Claim key = decodedJWT.getClaim("user");
            return key.asString();
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (JWTVerificationException e) {
            throw new RuntimeException(e);
        }

    }
}
